package monster.com.cvh.fragment;

import android.app.Activity;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import monster.com.cvh.R;
import monster.com.cvh.bean.OccupationIntentBean;
import monster.com.cvh.bean.PickDataBean;
import monster.com.cvh.bean.ResultBean;
import monster.com.cvh.event.RefreshCompletedEvent;
import monster.com.cvh.fragment.base.ResumeInfoBaseFragment;
import monster.com.cvh.util.CheckNetUtils;
import monster.com.cvh.util.KeyboardUtils;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: 13580
 * @data: 2018/3/19
 * @function:求职意向fragment
 */

public class OccupationIntentFragment extends ResumeInfoBaseFragment {
    private static final String TAG = "OccupationIntentFragmen";
    @BindView(R.id.tv_include_top_bar_title)
    TextView mTvTitle;
    @BindView(R.id.tv_fragment_occupation_intent_work_type_choose)
    TextView mTvWorkType;
    @BindView(R.id.edt_fragment_occupation_profession)
    EditText mEdtProfession;
    @BindView(R.id.edt_fragment_occupation_job)
    EditText mEdtJob;
    @BindView(R.id.edt_fragment_occupation_city)
    EditText mEdtCity;
    @BindView(R.id.edt_fragment_occupation_salary)
    EditText mEdtSalary;
    private List<PickDataBean> mWorkTypeBeans = new ArrayList<>();
    private OptionsPickerView mPVWorkType;
    private OccupationIntentBean.DataBean mBean;
    private OccupationIntentBean.DataBean mCloneBean;

    public static OccupationIntentFragment newInstance() {
        OccupationIntentFragment fragment = new OccupationIntentFragment();
        return fragment;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_occupation_intent;
    }

    @Override
    protected void initData() {
        mWorkTypeBeans.add(new PickDataBean(getResources().getString(R.string.fragment_occupation_intent_full_job), 0));
        mWorkTypeBeans.add(new PickDataBean(getResources().getString(R.string.fragment_occupation_intent_practice), 1));
        mWorkTypeBeans.add(new PickDataBean(getResources().getString(R.string.fragment_occupation_intent_part_time_job), 2));
        mDialog.show();
        OkGo.<String>get(MyConstant.GET_RESUME_PREFER_JOB).tag(this)
                .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            OccupationIntentBean bean = new Gson().fromJson(s, OccupationIntentBean.class);
                            if (bean != null && bean.getCode() == 1) {
                                mBean = bean.getData();
                                if (mBean.getWork_type().isEmpty()){
                                    mBean.setWork_type(getString(R.string.fragment_occupation_intent_full_job));
                                }
                                mCloneBean = (OccupationIntentBean.DataBean) mBean.clone();
                                Log.e(TAG, "返回的数据: '" + mBean.toString());
                                initViewData();
                            } else {
                                showToastShort(R.string.net_load_failed);
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                            showToastShort(R.string.net_load_failed);
                        } finally {
                            mDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        mDialog.dismiss();
                        showToastShort(R.string.net_load_failed);
                    }
                });
    }

    @Override
    protected void initEvent() {
        mTvTitle.setText(R.string.fragment_occupation_intent_title);
    }

    private void initViewData() {
        initPickDate();
        mEdtProfession.setText(mBean.getIndustry());
        mEdtJob.setText(mBean.getPosition());
        mEdtSalary.setText(mBean.getSalary());
        mEdtCity.setText(mBean.getWork_city());
        if (mBean.getWork_type().isEmpty()) {
            mBean.setWork_type(getString(R.string.fragment_occupation_intent_full_job));
        }
        mTvWorkType.setText(mBean.getWork_type());
        mTvWorkType.setTextColor(getActivity().getResources().getColor(R.color.tv_title));

        mEdtProfession.addTextChangedListener(new CustomerTextWatcher(mEdtProfession.getId()));
        mEdtJob.addTextChangedListener(new CustomerTextWatcher(mEdtJob.getId()));
        mEdtSalary.addTextChangedListener(new CustomerTextWatcher(mEdtSalary.getId()));
        mEdtCity.addTextChangedListener(new CustomerTextWatcher(mEdtCity.getId()));
    }

    private void initPickDate() {
        mPVWorkType = new OptionsPickerView.Builder(getActivity(), new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                String workType = mWorkTypeBeans.get(options1).getPickerViewText();
                mTvWorkType.setText(workType);
                mTvWorkType.setTextColor(getActivity().getResources().getColor(R.color.tv_title));
                mBean.setWork_type(workType);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final ImageView ivSubmit = (ImageView) v.findViewById(R.id.iv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        ivSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPVWorkType.returnData();
                                mPVWorkType.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPVWorkType.dismiss();
                            }
                        });
                    }
                })
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.line_color))
                .setLineSpacingMultiplier(2.0f)
                .setDecorView((ViewGroup) getActivity().getWindow().getDecorView())
                .build();
        mPVWorkType.setPicker(mWorkTypeBeans);//添加数据
        int selecedIndex = getSelecedIndex(mBean.getWork_type());
        mPVWorkType.setSelectOptions(selecedIndex);
    }

    private int getSelecedIndex(String content) {
        if (mWorkTypeBeans != null) {
            for (int i = 0; i < mWorkTypeBeans.size(); i++) {
                String name = mWorkTypeBeans.get(i).getName();
                if (name.equals(content)) {
                    return i;
                }
            }
        }
        return 0;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

    @OnClick({R.id.iv_include_top_bar_back, R.id.tv_include_top_bar_save, R.id.rel_fragment_occupation_intent_pick_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_include_top_bar_back:
                isSaveOnExit();
                break;
            case R.id.tv_include_top_bar_save:
                saveInfoData();
                break;
            case R.id.rel_fragment_occupation_intent_pick_date:
                KeyboardUtils.hideSoftInput((Activity) mContext);
                mPVWorkType.show();
                break;
        }
    }

    private void isSaveOnExit() {
        if (!isDataChanged()) {
            mAlertDialog.show();
        } else {
            KeyboardUtils.hideSoftInput((Activity) mContext);
            ((Activity)mContext).finish();
        }
    }

    @Override
    protected void saveInfoData() {
        if (!CheckNetUtils.checkState_21()){
            InfoUnCompeledDialogFragment.getInstance(getString(R.string.net_offline)).show(getFragmentManager(),"net_offline");
            return;
        }
        if (!isDataChanged()) {
            mDialog.show();
            OkGo.<String>put(MyConstant.MODIFY_RESUME_PREFER_JOB).tag(this)
                    .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                    .params(MyConstant.INDUSTRY, mBean.getIndustry())
                    .params(MyConstant.POSITION, mBean.getPosition())
                    .params(MyConstant.SALARY, mBean.getSalary())
                    .params(MyConstant.WORK_CITY, mBean.getWork_city())
                    .params(MyConstant.WORK_TYPE, mBean.getWork_type())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            try {
                                ResultBean resultBean = new Gson().fromJson(s, ResultBean.class);
                                if (resultBean.getCode() == 1) {
                                    showToastShort(R.string.net_save_success);
                                    //通知刷新完成度
                                    RefreshCompletedEvent.getInstance().onRefreshCompleted();
                                    getActivity().finish();
                                } else {
                                    showToastShort(R.string.net_load_failed);
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                showToastShort(R.string.net_load_failed);
                            } finally {
                                mDialog.dismiss();
                                KeyboardUtils.hideSoftInput((Activity) mContext);
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            showToastShort(R.string.net_load_failed);
                            mDialog.dismiss();
                        }
                    });
        } else {
            KeyboardUtils.hideSoftInput((Activity) mContext);
            ((Activity)mContext).finish();
        }
    }

    @Override
    public boolean isDataChanged() {
        if (mBean == null || mCloneBean == null) {
            return true;
        }
        return mBean.equals(mCloneBean);
    }

    @Override
    public void onExit() {
        isSaveOnExit();
    }

    protected class CustomerTextWatcher implements TextWatcher {
        private int viewId;

        public CustomerTextWatcher(@IdRes int viewId) {
            this.viewId = viewId;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String str = editable.toString();
            switch (viewId) {
                case R.id.edt_fragment_occupation_profession:
                    mBean.setIndustry(str);
                    break;
                case R.id.edt_fragment_occupation_job:
                    mBean.setPosition(str);
                    break;
                case R.id.edt_fragment_occupation_city:
                    mBean.setWork_city(str);
                    break;
                case R.id.edt_fragment_occupation_salary:
                    mBean.setSalary(str);
                    break;

            }
        }
    }
}
